// 引入工具类
const { articleApi } = require('../../utils/api')
const { formatTime } = require('../../utils/dateUtils')
const { newsStore } = require('../../utils/store')
const { extractImageFromHtml } = require('../../utils/imageUtils')

Page({
  data: {
    // 搜索相关
    searchKeyword: '',
    showHistory: true,
    searchHistory: [],
    hotTags: ['学院', '马克思', '活动', '通知', '讲座'],

    // 筛选条件
    selectedCategory: '',
    selectedSection: '',
    categories: [],
    sections: [],
    categoryOptions: [{ text: '全部分类', value: '' }],
    sectionOptions: [{ text: '全部学院', value: '' }],

    // 搜索结果
    searchResults: [],
    loading: false,
    finished: false,
    refreshing: false,
    error: false,
    currentPage: 1,
    pageSize: 10,

    // 翻页器相关
    totalPages: 1,
    totalResults: 0,
    showPagination: false,
    pageInput: 1
  },

  onLoad(options) {
    console.log('搜索页面加载，参数:', options)

    // 加载搜索历史
    this.loadSearchHistory()

    // 获取筛选选项
    this.fetchFilters()

    // 检查URL参数
    if (options.keyword) {
      this.setData({
        searchKeyword: options.keyword,
        showHistory: false
      })
      this.performSearch()
    }
  },

  onShow() {
    console.log('搜索页面显示')
  },

  // 加载搜索历史
  loadSearchHistory() {
    try {
      const history = wx.getStorageSync('searchHistory') || []
      this.setData({
        searchHistory: history.slice(0, 10) // 限制显示数量
      })
    } catch (error) {
      console.error('加载搜索历史失败:', error)
    }
  },

  // 获取筛选选项
  async fetchFilters() {
    try {
      console.log('开始获取筛选选项')

      // 获取分类列表
      const categoriesResponse = await articleApi.getAllCategories()
      console.log('分类API响应:', categoriesResponse)

      let categories = []
      if (categoriesResponse && categoriesResponse.code === 200) {
        categories = categoriesResponse.data || []
      } else if (Array.isArray(categoriesResponse)) {
        categories = categoriesResponse
      } else if (categoriesResponse && categoriesResponse.data) {
        categories = categoriesResponse.data
      }

      const categoryOptions = [
        { text: '全部分类', value: '' },
        ...categories.map(item => ({
          text: typeof item === 'string' ? item : (item.name || item.categoryName || item),
          value: typeof item === 'string' ? item : (item.name || item.categoryName || item)
        }))
      ]

      console.log('处理后的分类选项:', categoryOptions)

      // 获取学院列表
      let sections = []
      let sectionOptions = [{ text: '全部学院', value: '' }]

      try {
        const sectionsResponse = await articleApi.getAllSections()
        console.log('学院API响应:', sectionsResponse)

        if (sectionsResponse && sectionsResponse.code === 200) {
          sections = sectionsResponse.data || []
        } else if (Array.isArray(sectionsResponse)) {
          sections = sectionsResponse
        } else if (sectionsResponse && sectionsResponse.data) {
          sections = sectionsResponse.data
        }

        sectionOptions = [
          { text: '全部学院', value: '' },
          ...sections.map(item => ({
            text: typeof item === 'string' ? item : (item.name || item.sectionName || item),
            value: typeof item === 'string' ? item : (item.name || item.sectionName || item)
          }))
        ]

        console.log('处理后的学院选项:', sectionOptions)
      } catch (error) {
        console.error('获取学院列表失败:', error)
      }

      this.setData({
        categories,
        sections,
        categoryOptions,
        sectionOptions
      })

      console.log('筛选选项设置完成:', {
        categoriesCount: categories.length,
        sectionsCount: sections.length,
        categoryOptionsCount: categoryOptions.length,
        sectionOptionsCount: sectionOptions.length
      })

      // 保存到全局状态
      newsStore.setCategories(categories)
      newsStore.setSections(sections)

    } catch (error) {
      console.error('获取筛选选项失败:', error)
    }
  },

  // 搜索输入变化
  onSearchChange(event) {
    const keyword = event.detail
    this.setData({
      searchKeyword: keyword,
      showHistory: keyword === ''
    })
  },

  // 清空搜索
  onSearchClear() {
    this.setData({
      searchKeyword: '',
      showHistory: true,
      searchResults: [],
      finished: false,
      currentPage: 1
    })
  },

  // 执行搜索
  async performSearch() {
    const keyword = this.data.searchKeyword.trim()
    if (!keyword) {
      this.setData({
        showHistory: true,
        searchResults: [],
        finished: false,
        currentPage: 1,
        loading: false
      })
      return
    }

    // 添加到搜索历史
    this.saveSearchHistory(keyword)

    // 重置搜索状态
    this.setData({
      showHistory: false,
      searchResults: [],
      currentPage: 1,
      finished: false,
      error: false,
      loading: true
    })

    // 执行搜索
    await this.searchArticles(true)
  },

  // 搜索文章
  async searchArticles(isRefresh = false) {
    try {
      console.log('=== 开始搜索文章 ===')
      console.log('搜索模式:', isRefresh ? '刷新搜索' : '加载更多')
      console.log('当前页面状态:', {
        currentPage: this.data.currentPage,
        searchKeyword: this.data.searchKeyword,
        selectedCategory: this.data.selectedCategory,
        selectedSection: this.data.selectedSection,
        loading: this.data.loading,
        finished: this.data.finished
      })

      if (isRefresh) {
        console.log('执行刷新操作，重置搜索状态')
        this.setData({
          currentPage: 1,
          searchResults: [],
          finished: false,
          error: false
        })
      }

      this.setData({ loading: true })

      // 构建搜索参数 - 与PC版保持一致的格式
      const keyword = this.data.searchKeyword ? this.data.searchKeyword.trim() : ''
      const category = this.data.selectedCategory ? this.data.selectedCategory.trim() : ''
      const section = this.data.selectedSection ? this.data.selectedSection.trim() : ''

      const params = {
        keyword: keyword || undefined,
        category: category || undefined,
        section: section || undefined,
        pageNum: this.data.currentPage,
        pageSize: this.data.pageSize
      }

      console.log('=== 搜索参数验证 ===')
      console.log('原始搜索关键词:', `"${this.data.searchKeyword}"`)
      console.log('处理后关键词:', `"${params.keyword}"`)
      console.log('关键词长度:', params.keyword.length)
      console.log('关键词编码测试:', encodeURIComponent(params.keyword))
      console.log('完整搜索参数:', JSON.stringify(params, null, 2))

      // 验证参数有效性
      if (!params.keyword || params.keyword.length === 0) {
        console.warn('⚠️ 搜索关键词为空，终止搜索')
        this.setData({ loading: false })
        return
      }

      console.log('=== 发起API请求 ===')
      console.log('请求时间:', new Date().toISOString())

      let response
      // 根据是否有筛选条件选择合适的API
      const hasCategory = params.category && params.category.trim()
      const hasSection = params.section && params.section.trim()

      if (hasCategory || hasSection) {
        // 有筛选条件，使用高级搜索API
        console.log('使用高级搜索API: /api/articles/search/advanced')
        response = await articleApi.searchWithMultipleConditions(params)
      } else {
        // 只有关键词，使用基础搜索API
        console.log('使用基础搜索API: /api/articles/search')
        response = await articleApi.searchArticles({
          keyword: params.keyword,
          pageNum: params.pageNum,
          pageSize: params.pageSize
        })
      }

      console.log('=== API响应详情 ===')
      console.log('响应时间:', new Date().toISOString())
      console.log('响应类型:', typeof response)
      console.log('响应是否为null/undefined:', response === null || response === undefined)
      console.log('完整响应数据:', JSON.stringify(response, null, 2))

      let searchResults = []
      let hasMore = false

      console.log('=== 响应数据结构分析 ===')
      if (response) {
        console.log('响应对象属性:', Object.keys(response))
        console.log('response.list存在:', 'list' in response)
        console.log('response.list类型:', typeof response.list)
        console.log('response.list是数组:', Array.isArray(response.list))
        if (response.list) {
          console.log('response.list长度:', response.list.length)
          if (response.list.length > 0) {
            console.log('第一个元素示例:', JSON.stringify(response.list[0], null, 2))
          }
        }
        console.log('response.total:', response.total)
        console.log('response.pages:', response.pages)
        console.log('response.pageNum:', response.pageNum)
        console.log('response.pageSize:', response.pageSize)
      } else {
        console.error('❌ 响应为空或null')
      }

      // 处理API响应 - 直接分页格式 {list: Array, total: 169, pageNum: 1, pageSize: 10, pages: 17}
      if (response && response.list && Array.isArray(response.list)) {
        console.log('✅ 响应格式验证通过')
        const rawList = response.list
        const totalPages = response.pages || 1
        const currentPageNum = response.pageNum || 1

        console.log('=== 响应数据解析 ===')
        console.log('原始数据列表长度:', rawList.length)
        console.log('当前页码:', currentPageNum)
        console.log('总页数:', totalPages)
        console.log('总记录数:', response.total)

        if (rawList.length === 0) {
          console.warn('⚠️ API返回空列表，可能的原因:')
          console.warn('1. 搜索关键词无匹配结果')
          console.warn('2. 筛选条件过于严格')
          console.warn('3. 数据库中无相关数据')
          console.warn('4. 后端搜索逻辑问题')
        }

        // 映射搜索结果数据
        console.log('=== 开始数据映射 ===')
        searchResults = rawList.map((item, index) => {
          console.log(`处理第${index + 1}条数据:`, {
            newsId: item.newsId,
            title: item.title,
            contentPreview: item.contentPreview ? item.contentPreview.substring(0, 50) + '...' : '无',
            category: item.category,
            section: item.section,
            pubTime: item.pubTime
          })

          const mappedItem = {
            newsId: item.newsId,
            id: item.newsId,
            title: item.title || '无标题',
            contentPreview: item.contentPreview || '无内容摘要',
            contentText: item.contentPreview || '',
            category: item.category || '未分类',
            section: item.section || '',
            pubTime: item.pubTime,
            formattedTime: formatTime(item.pubTime),
            image: this.extractImage(item.contentHtml || '')
          }

          return mappedItem
        })

        console.log('数据映射完成，映射结果数量:', searchResults.length)

        // 翻页器模式：每次都替换结果，不累加
        const currentList = searchResults

        console.log('=== 更新页面状态 ===')
        console.log('是否刷新模式:', isRefresh)
        console.log('新增结果数量:', searchResults.length)
        console.log('合并后总数量:', currentList.length)
        console.log('是否还有更多:', hasMore)
        console.log('下一页页码:', this.data.currentPage + 1)

        this.setData({
          searchResults: currentList,
          loading: false,
          error: false,
          finished: false,
          // 翻页器相关数据
          totalPages: totalPages,
          totalResults: response.total || 0,
          showPagination: true,
          pageInput: this.data.currentPage // 使用当前设置的页码，而不是响应中的页码
        })

        // 保存到全局状态
        newsStore.setSearchResults(currentList, !isRefresh)

        console.log('✅ 搜索结果处理完成:', {
          resultCount: searchResults.length,
          totalCount: currentList.length,
          hasMore,
          currentPage: currentPageNum,
          totalPages,
          finished: !hasMore
        })
      } else {
        // 无效响应或空结果
        console.error('❌ 搜索API响应格式异常')
        console.error('响应验证失败的原因:')
        console.error('- response存在:', !!response)
        console.error('- response.list存在:', !!(response && response.list))
        console.error('- response.list是数组:', !!(response && response.list && Array.isArray(response.list)))

        this.setData({
          searchResults: isRefresh ? [] : this.data.searchResults,
          loading: false,
          error: false,
          finished: true
        })
      }

    } catch (error) {
      console.error('搜索失败:', error)
      this.setData({
        loading: false,
        error: true
      })
      wx.showToast({
        title: '搜索失败',
        icon: 'error'
      })
    }
  },

  // 生成摘要
  generateSummary(content) {
    if (!content) return '无内容摘要'
    // 移除HTML标签
    const text = content.replace(/<[^>]*>/g, '')
    return text.length > 80 ? text.substring(0, 80) + '...' : text
  },

  // 提取图片
  extractImage(htmlContent) {
    return extractImageFromHtml(htmlContent)
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword || !keyword.trim()) return

    try {
      let history = this.data.searchHistory
      // 去重
      history = history.filter(item => item !== keyword)
      history.unshift(keyword)
      // 限制数量
      history = history.slice(0, 10)

      this.setData({
        searchHistory: history
      })

      wx.setStorageSync('searchHistory', history)
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  },

  // 通过历史记录搜索
  searchByHistory(event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({
      searchKeyword: keyword,
      showHistory: false
    })
    this.performSearch()
  },

  // 通过热门标签搜索
  searchByTag(event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({
      searchKeyword: keyword,
      showHistory: false
    })
    this.performSearch()
  },

  // 清空搜索历史
  clearHistory() {
    const that = this
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有搜索历史吗？',
      success(res) {
        if (res.confirm) {
          that.setData({
            searchHistory: []
          })
          wx.removeStorageSync('searchHistory')
          wx.showToast({
            title: '已清空搜索历史',
            icon: 'success'
          })
        }
      }
    })
  },

  // 处理分类变化
  handleCategoryChange(event) {
    const selectedCategory = event.detail
    console.log('分类变化:', selectedCategory)
    this.setData({ selectedCategory })

    // 如果有搜索关键词，重新搜索
    if (this.data.searchKeyword && !this.data.showHistory) {
      this.performSearch()
    }
  },

  // 处理学院变化
  handleSectionChange(event) {
    const selectedSection = event.detail
    console.log('学院变化:', selectedSection)
    this.setData({ selectedSection })

    // 如果有搜索关键词，重新搜索
    if (this.data.searchKeyword && !this.data.showHistory) {
      this.performSearch()
    }
  },

  // 下拉刷新
  async onRefresh() {
    console.log('触发下拉刷新')
    this.setData({ refreshing: true })

    try {
      await this.searchArticles(true)
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('刷新失败:', error)
      wx.showToast({
        title: '刷新失败',
        icon: 'error'
      })
    } finally {
      this.setData({ refreshing: false })
    }
  },

  // 上拉加载更多
  async onLoad() {
    console.log('触发上拉加载，当前状态:', {
      finished: this.data.finished,
      loading: this.data.loading,
      currentPage: this.data.currentPage,
      searchKeyword: this.data.searchKeyword,
      showHistory: this.data.showHistory
    })

    // 检查是否应该跳过加载
    if (this.data.finished || this.data.loading) {
      console.log('跳过加载：已完成或正在加载中')
      return
    }

    // 检查是否有有效的搜索条件
    if (this.data.showHistory || !this.data.searchKeyword || !this.data.searchKeyword.trim()) {
      console.log('跳过加载：没有有效的搜索条件')
      return
    }

    // 检查是否已有搜索结果（防止初始化时意外触发）
    if (this.data.searchResults.length === 0) {
      console.log('跳过加载：没有现有搜索结果')
      return
    }

    await this.searchArticles(false)
  },

  // 翻页器相关方法
  // 切换页码
  changePage(page) {
    console.log('切换页码:', page)

    // 验证页码范围
    if (page < 1 || page > this.data.totalPages) {
      console.warn('页码超出范围:', page)
      return
    }

    // 重置搜索状态，设置新的页码
    this.setData({
      currentPage: page,
      searchResults: [],
      finished: false,
      error: false,
      loading: true,
      pageInput: page
    })

    // 执行搜索（翻页器模式，总是刷新）
    this.searchArticles(true)

    // 滚动到顶部
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  // 上一页
  prevPage() {
    if (this.data.currentPage > 1) {
      this.changePage(this.data.currentPage - 1)
    }
  },

  // 下一页
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.changePage(this.data.currentPage + 1)
    }
  },

  // 首页
  firstPage() {
    this.changePage(1)
  },

  // 末页
  lastPage() {
    this.changePage(this.data.totalPages)
  },

  // 跳转到指定页码
  goToPage() {
    const page = parseInt(this.data.pageInput)
    if (!page || page < 1) {
      this.setData({ pageInput: 1 })
      return
    }
    if (page > this.data.totalPages) {
      this.setData({ pageInput: this.data.totalPages })
      return
    }
    this.changePage(page)
  },

  // 页码输入变化
  onPageInputChange(event) {
    this.setData({
      pageInput: event.detail.value
    })
  },

  // 跳转到新闻详情
  goToDetail(event) {
    try {
      const newsId = event.currentTarget.dataset.newsId
      console.log('跳转新闻详情:', newsId)

      if (!newsId) {
        wx.showToast({
          title: '文章ID无效',
          icon: 'error'
        })
        return
      }

      // 添加到历史记录
      const newsItem = this.data.searchResults.find(item =>
        (item.newsId || item.id) == newsId
      )

      if (newsItem) {
        const app = getApp()
        app.addHistory(newsItem)
      }

      wx.navigateTo({
        url: `/pages/news/detail/detail?id=${newsId}`
      })

    } catch (error) {
      console.error('跳转新闻详情失败:', error)
      wx.showToast({
        title: '跳转失败',
        icon: 'error'
      })
    }
  }
})
